<template>
  <el-dialog v-model="visible" title="选择社区分类" width="80%" :before-close="handleClose">
    <!-- 搜索栏 -->
    <div class="handle-box">
      <el-input v-model="searchForm.categoryName" placeholder="社区分类名称" class="handle-input mr10" clearable />
      <el-button type="primary" icon="el-icon-search" @click="handleSearch">搜索</el-button>
    </div>

    <!-- 表格 -->
    <el-table :data="tableData" border class="table" ref="categoryTable" header-cell-class-name="table-header"
      row-key="id" @row-click="handleRowClick" :row-class-name="getRowClassName">
      <el-table-column label="选择" width="80" align="center">
        <template #default="scope">
          <el-radio v-model="selectedCategoryId" :label="scope.row.id" @change="handleRadioChange(scope.row)">
            <span></span>
          </el-radio>
        </template>
      </el-table-column>
      <el-table-column prop="id" label="社区分类ID" width="120" />
      <el-table-column prop="categoryName" label="社区分类名称" />
      <el-table-column prop="createTime" label="创建时间">
        <template #default="scope">
          {{ scope.row.createTime ? dateFormat(scope.row.createTime) : '-' }}
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination">
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
        :current-page="pagination.currentPage" :page-sizes="[10, 20, 50, 100]" :page-size="pagination.pageSize"
        layout="total, sizes, prev, pager, next, jumper" :total="pagination.total">
      </el-pagination>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <span class="selected-info">{{ selectedCategory ? `已选择：${selectedCategory.categoryName}` : '请选择社区分类' }}</span>
        <div>
          <el-button @click="handleClose">取消</el-button>
          <el-button type="primary" @click="handleConfirm" :disabled="!selectedCategory">确定</el-button>
        </div>
      </div>
    </template>
  </el-dialog>
</template>

<script>
import moment from "moment";
import { getForumCategories } from "@/api/content";

export default {
  name: "SelectCommunityClass",
  props: {
    modelValue: {
      type: Boolean,
      default: false
    },
    // 已选中的社区分类数据
    selectedData: {
      type: Object,
      default: null
    }
  },
  emits: ['update:modelValue', 'confirm'],
  data() {
    return {
      searchForm: {
        categoryName: "",
      },
      tableData: [],
      selectedCategory: null, // 当前选中的社区分类
      selectedCategoryId: null, // 当前选中的社区分类ID
      // 分页相关
      pagination: {
        currentPage: 1,
        pageSize: 10,
        total: 0
      }
    };
  },
  computed: {
    visible: {
      get() {
        return this.modelValue;
      },
      set(val) {
        this.$emit('update:modelValue', val);
      }
    }
  },
  watch: {
    visible(newVal) {
      if (newVal) {
        this.getData();
        this.initSelectedData();
      }
    }
  },
  methods: {
    dateFormat(val) {
      return val ? moment(val).format("YYYY-MM-DD HH:mm:ss") : "";
    },
    handleSearch() {
      this.pagination.currentPage = 1;
      this.getData();
    },
    // 分页相关方法
    handleSizeChange(val) {
      this.pagination.pageSize = val;
      this.pagination.currentPage = 1;
      this.getData();
    },
    handleCurrentChange(val) {
      this.pagination.currentPage = val;
      this.getData();
    },
    buildSearchParams() {
      const params = {
        limit: this.pagination.pageSize,
        offset: this.pagination.currentPage
      };

      if (this.searchForm.categoryName) {
        params.categoryName = this.searchForm.categoryName;
      }

      return params;
    },
    async getData() {
      try {
        const params = this.buildSearchParams();
        const response = await getForumCategories(params);

        if (response && response.data) {
          this.tableData = response.data.rows || response.data;

          if (response.data.total !== undefined) {
            this.pagination.total = response.data.total;
          }

          // 数据加载完成后，设置已选中的数据
          this.$nextTick(() => {
            this.setSelectedRow();
          });
        }
      } catch (error) {
        console.error('获取社区分类数据失败:', error);
        this.$message.error('获取社区分类数据失败');
      }
    },
    // 初始化已选中的数据
    initSelectedData() {
      this.selectedCategory = this.selectedData;
      this.selectedCategoryId = this.selectedData ? this.selectedData.id : null;
    },
    // 设置表格中已选中的行（radio模式下不需要）
    setSelectedRow() {
      // radio模式下不需要设置表格选中状态
    },
    // 处理radio选择变化
    handleRadioChange(row) {
      this.selectedCategory = row;
      this.selectedCategoryId = row.id;
    },
    // 处理行点击事件
    handleRowClick(row) {
      this.selectedCategory = row;
      this.selectedCategoryId = row.id;
    },
    // 获取行的class名称，用于高亮选中行
    getRowClassName({ row }) {
      return this.selectedCategoryId === row.id ? 'selected-row' : '';
    },
    // 关闭弹窗
    handleClose() {
      this.visible = false;
    },
    // 确认选择
    handleConfirm() {
      this.$emit('confirm', this.selectedCategory);
      this.handleClose();
    }
  },
};
</script>

<style lang='scss' scoped>
.handle-box {
  margin-bottom: 20px;
}

.handle-select {
  width: 120px;
}

.handle-input {
  width: 200px;
  display: inline-block;
}

.table {
  width: 100%;
  font-size: 14px;
}

.mr10 {
  margin-right: 10px;
}

.pagination {
  margin-top: 20px;
  text-align: right;
}

.dialog-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.selected-info {
  color: #606266;
  font-size: 14px;
}

::v-deep .el-date-editor {
  margin-right: 10px;
  width: 300px;
}

// 选中行的样式
::v-deep .selected-row {
  background-color: #f0f9ff !important;
}

// 鼠标悬停时的指针样式
::v-deep .el-table__row {
  cursor: pointer;
}
</style>